<?php

namespace App\Http\Controllers\Api;
use App\Blocks\OrderBlock;
use App\Blocks\User;
use App\Http\Controllers\Controller;
use App\Libs\ResponseMessage;
use App\Models\OrderAddress;
use App\Models\Orders;
use EasyWeChat\Factory;
use Illuminate\Http\Request;

class OrderController extends Controller {

    public function updateCart(Request $request){
        if(
            !$request->has('g_id') ||
            !$request->has('buy_num')
        ){
            return response()->json(ResponseMessage::getInstance()->failed('PARAM_ERROR')->response());
        }

        global $g_uid;

        $gId = $request->get('g_id');
        $buyNum = $request->get('buy_num');

        $orderBlock = new OrderBlock();

        $status = $orderBlock->updateCart($g_uid, $gId, $buyNum);

        if($status === true){
            return response()->json(ResponseMessage::getInstance()->success()->response());
        }else{
            if($status === -1){
                return response()->json(ResponseMessage::getInstance()->failed('RESOURCES_NOT_EXIST')->response());
            }elseif ($status === -2){
                return response()->json(ResponseMessage::getInstance()->failed('LOW_STOCKS')->response());
            }else{
                return response()->json(ResponseMessage::getInstance()->failed()->response());
            }
        }
    }

    public function cart(){
        global $g_uid;
        $orderBlock = new OrderBlock();
        $cart = $orderBlock->cart($g_uid);
        return response()->json(ResponseMessage::getInstance()->success($cart)->response());
    }

    public function createOrder(Request $request){
        global $g_uid;
        $goodsIds = explode(',', $request->get('g_id'));
        if(!$goodsIds){
            return response()->json(ResponseMessage::getInstance()->failed('PARAM_ERROR')->response());
        }

        $orderBlock = new OrderBlock();

        $orderId = $orderBlock->createOrder($g_uid, $goodsIds);
        if($orderId){
            return response()->json(ResponseMessage::getInstance()->success($orderId)->response());
        }else{
            return response()->json(ResponseMessage::getInstance()->failed()->response());
        }
    }

    public function buyNow(Request $request){
        global $g_uid;
        $goodsId = $request->get('g_id');
        if(!$goodsId){
            return response()->json(ResponseMessage::getInstance()->failed('PARAM_ERROR')->response());
        }

        $orderBlock = new OrderBlock();

        $orderId = $orderBlock->createOrder($g_uid, [$goodsId]);
        if($orderId){
            return response()->json(ResponseMessage::getInstance()->success($orderId)->response());
        }else{
            return response()->json(ResponseMessage::getInstance()->failed()->response());
        }
    }

    public function getMyOrder(Request $request){
        global $g_uid;
        $page = $request->get('page', 1);
        $pageSize = $request->get('pageSize', 20);

        $search = ['user_id' => $g_uid];
        if($request->has('status')){
            $search['status'] = $request->get('status');
        }

        $orderBlock = new OrderBlock();

        $order = $orderBlock->getOrder($search, $page, $pageSize);
        return response()->json(ResponseMessage::getInstance()->success($order)->response());

    }

    public function getOrderDetail($orderId){
        $orderBlock = new OrderBlock();
        $order = $orderBlock->getOrderDetail($orderId);
        return response()->json(ResponseMessage::getInstance()->success($order)->response());
    }

    public function updateOrderAddress(Request $request){
        global $g_uid;
        if(!$request->has('o_id') || !$request->has('a_id')){
            return response()->json(ResponseMessage::getInstance()->failed('PARAM_ERROR')->response());
        }

        $addressId = $request->get('a_id');
        $orderId = $request->get('o_id');

        $userBlock = new User();
        $address = $userBlock->getUserAddressInfo($g_uid, $addressId);
        if(!$address){
            return response()->json(ResponseMessage::getInstance()->failed()->response());
        }

        $data = [
            'o_id'          => $orderId,
            'name'          => $address->name,
            'mobile'        => $address->mobile,
            'province'      => $address->province,
            'city'          => $address->city,
            'district'      => $address->district,
            'address'       => $address->address,
            'a_id'          => $address->id
        ];

        $orderAddress = OrderAddress::where('o_id', $orderId)->first();
        if($orderAddress){
            unset($data['o_id']);
            if(OrderAddress::where('o_id', $orderId)->update($data) === false){
                return response()->json(ResponseMessage::getInstance()->failed()->response());
            }else{
                return response()->json(ResponseMessage::getInstance()->success()->response());
            }
        }else{
            $orderAddressModel = new OrderAddress();
            if($orderAddressModel->saveData($data)){
                return response()->json(ResponseMessage::getInstance()->success()->response());
            }else{
                return response()->json(ResponseMessage::getInstance()->failed()->response());
            }
        }
    }

    public function wechatPay(Request $request){
        $config = \Config::get('wechat.payment.default');
        $app = Factory::payment($config);
        $app->handlePaidNotify(function ($message, $fail) {
            \Log::debug(json_encode($message));
            $outTradeNo = $message['out_trade_no'];
            $order = Orders::where('out_trade_no', $outTradeNo)->whereNull('pay_time')->first();

            if(!$order){
                return true;
            }

            if($message['return_code'] === 'SUCCESS'){
                if(array_get($message, 'result_code') === 'SUCCESS'){
                    $order->status = 1;
                    $order->pay_time = date('Y-m-d H:i:s', time());
                }
            }else{
                $fail('通信失败，请稍后再通知我');
            }

            $order->save();
        })->send();
    }


    public function prePay(Request $request){
        $orderId = $request->get('o_id');
        $remark = $request->get('remark', null);

        $orderBlock = new OrderBlock();

        $order = $orderBlock->getOrderDetail($orderId);
        if(!$order){
            return response()->json(ResponseMessage::getInstance()->failed('ORDER_NOT_EXIST')->response());
        }

        //没有地址
        if(!$order->a_id){
            return response()->json(ResponseMessage::getInstance()->setFailedCode('ADDRESS_NOT_FOUND', '没有选择地址')->response());
        }

        if($order->status != 0){
            return response()->json(ResponseMessage::getInstance()->setFailedCode('ORDER_STATUS_ERROR', '订单状态不对')->response());
        }

        $config = \Config::get('wechat.payment.default');
        $app = Factory::payment($config);
        global $g_wx_openid;

        $outTradeNo = date('YmdHis', time()).$order->id.getSalt(4, 1);
        $result = $app->order->unify([
            'body' => '果小贱平台购买商品',
            'out_trade_no' => $outTradeNo,
            'total_fee' => $order->pay_total * 100,
//            'total_fee' => 1,
            'notify_url' => env('APP_URL').'/api/pay/wechat', // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            'trade_type' => 'JSAPI',
            'openid' => $g_wx_openid,
        ]);



        if($result && $result['return_code'] === 'SUCCESS' && $result['return_msg'] === 'OK'){
            $orderUpdate = [
                'out_trade_no' => $outTradeNo
            ];
            if($remark){
                $orderUpdate['remark'] = $remark;
            }
            if(Orders::where('id', $orderId)->update($orderUpdate) === false){
                return response()->json(ResponseMessage::getInstance()->setFailedCode('REMARK_SAVE_FAILD', '更新订单失败')->response());
            }
            $jssdk = $app->jssdk->bridgeConfig($result['prepay_id']);
            if($jssdk){
                return response()->json(ResponseMessage::getInstance()->success($jssdk)->response());
            }else{
                \Log::error('product jssdk'.json_encode($jssdk));
                return response()->json(ResponseMessage::getInstance()->failed()->response());
            }
        }else{
            \Log::error('product prepay'.json_encode($result));
            return response()->json(ResponseMessage::getInstance()->failed()->response());
        }

    }

    public function cancelOrder(){

    }

}